/*global UE, jQuery, $, escape, unescape */
/*jslint devel: true, browser: true, undef: true, sloppy: true, regexp: true,
vars: true, nomen: true, white: true, maxlen: 160, indent: 4 */
////////////////////  UE JavaScript Library  ////////////////////
//Global Variable
var UE = UE || {};

//temp
UE.temp = UE.temp || {};

//config
UE.config = UE.config || {};
UE.config.debug = false;

//user
UE.user = UE.user || {};

//console
UE.log = function (input) {
	if (!UE.config || !UE.config.debug) {return false; }
	if (window.console) {
		console.log(input);
	} else {
		if (document.title.length + input.length > 90) {
			document.title = input;
		} else {
			document.title += '|' + input;
		}
	}
};

//string
UE.str = UE.str || {};
UE.str.cny = UE.str.rmb = '\xA5';  //'\xA5' means CNY (RMB) symbol.
UE.str.priceToNumber = function (s) {  //formats '[cny] 12,345.60' to 12345.6
	return s ? parseFloat(s.replace('\uffe5', '').replace(UE.str.cny, '').replace(/\,/g, '').replace(/\-\s+/, '-')) : 0;
	//'\uffe5' means [cny] in full-width chinese char
};
UE.str.numberToFullPrice = function (n) {  //formats 12345.6789 to '[cny] 12,345.68', -1234.567 to '- [cny] 1,234.57'
	return (n < 0 ? '- ' : '') + UE.str.cny + ' ' + Math.abs(n).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
	//this regexp formats '1234.56' to '1,234.56', decimal point is necessary in source string
};
UE.str.numberToFullPriceHTML = function (n) {  //formats 12345.6789 to '[cny] 12,345.68'
	return [
		(n < 0 ? '- ' : ''),
		'<samp>',
			UE.str.cny,
		'<\/samp> ',
		'<span>',
			Math.abs(n).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'),
		'<\/span>'
	].join('');
	//the regexp formats '1234.56' to '1,234.56', decimal point is necessary in source string
};
UE.str.ifHas = function(sA, sB) {return (sA.indexOf(sB) > -1); };
UE.str.ifStartsWith = function(sA, sB) {return (sA.indexOf(sB) === 0); };
UE.str.isHash = function(s) {return UE.str.ifStartsWith(s, '#'); };
UE.str.replaceVar = function (sTemplate, sVar, s) {
	if (sTemplate && sVar && s && UE.str.ifHas(sTemplate, sVar)) {
		var a = sTemplate.split(sVar);
		var aOutput = [a[0], s, a[1]];
		return aOutput.join('');
	}
	return false;
};
UE.str.trimInner = function (s) {
	return s.replace(/\s{2,}/g, ' ');
};
UE.str.reEmail = /^(?:[a-z\d]+[_\-\+\.]?)*[a-z\d]+@(?:([a-z\d]+\-?)*[a-z\d]+\.)+([a-z]{2,})+$/i;
UE.str.reMobile = /^1[358]\d{9}$/;
UE.str.rePostCode = /^\d{6}$/;


//url
UE.url = UE.url || {};
UE.url.isInFrame = window.self !== window.top;
UE.url.str = location.href;
UE.url.host = location.hostname.toLowerCase();  //without port number
if (UE.url.host === 'www.uemall.com' || UE.url.host === 'uemall.com') {
	UE.url.env = 'production';
} else if (UE.url.host === 'v2.ue.com') {
	UE.url.env = 'testing';
} else {
	UE.url.env = 'development';
}
UE.temp.urlLib = {
	development: {
		gaAccount: 'UA-20697969-3',
		rootDomain: UE.url.host,
		mediaSrv: UE.url.host,
		skinSrv: UE.url.host
	},
	testing: {
		gaAccount: 'UA-20697969-2',
		rootDomain: UE.url.host,
		mediaSrv: UE.url.host,
		skinSrv: UE.url.host
	},
	production: {
		gaAccount: 'UA-20697969-1',
		rootDomain: UE.url.host,
		mediaSrv: 'i1.uemall.com',
		skinSrv: 'skin.uemall.com'
	}
};
jQuery.extend(UE.url, UE.temp.urlLib[UE.url.env]);
delete UE.temp.urlLib;
//UE.url.rootDomain = UE.url.host.replace('www.', '');
UE.url.skinPath = '/skin/frontend/uemall_v2/default/';

UE.url.path = location.pathname;
UE.url.isCheckoutPage = UE.str.ifStartsWith(UE.url.path, '/checkout/');
UE.url.isHome = (UE.url.path === '/' || UE.str.ifStartsWith(UE.url.path, '/static/html/home/'));

UE.url.query = location.search.slice(1).replace(/&+$/, '');
UE.url.param = null;

UE.url.parseQuery = function(sQuery) {
	var data = {};
	if (sQuery) {
		var aQ = sQuery.split('&'), aP, sN, sV;
		jQuery.each(aQ, function(i, n) {
			aP = n.split('=');
			sN = aP[0];
			sV = aP[1] || '';
			if (sN /** && sV **/) {  //add this comment to keep empty key
				data[decodeURIComponent(sN).toLowerCase()] = decodeURIComponent(sV);
			}
		});
	}
	return data;
};
UE.url.getParam = function (s) {  //API: var sCode = UE.url.getParam('prdcode');
	if (!UE.url.param) {
		UE.url.param = UE.url.parseQuery(UE.url.query);
	}
	return (s && typeof s === 'string') ? UE.url.param[s.toLowerCase()] : false;
};
UE.url.open = function (s) {
	if (s && typeof s === 'string') {
		window.open(s);
	} else {
		return false;
	}
};
UE.url.go = function (s) {
	if (s && typeof s === 'string') {
		window.location.href = s;
	} else {
		return false;
	}
};
UE.url.getImg = function (s) {
	if (s && typeof s === 'string') {
		var oImg = new Image();
		oImg.src = s;
	} else {
		return false;
	}
};


//ua
UE.ua = UE.ua || {};
UE.ua.str = navigator.userAgent;
UE.ua.isIE6 = !jQuery.support.style && !UE.str.ifHas(UE.ua.str, 'MSIE 7');
UE.ua.isWebKit = UE.str.ifHas(UE.ua.str.toLowerCase(), 'webkit');


//cmAction
UE.actionBtn = {
	isReady: false,
	actionList: {},
	ini: function (s) {
		if (!this.isReady) {
			this._bind(s);
			this.isReady = true;
		}
	},
	_bind: function (s) {
		var sSelector = s || 'a.cmAction';
		var j = jQuery(sSelector);
		j.live('click', function () {
			var s = this.getAttribute('href', 2);
			s = UE.str.ifHas(s, '#') ? '#' + s.split('#')[1] : s;
			if (UE.str.isHash(s)) {
				//var jThis = jQuery(this);
				//if (jThis.hasClass('disabled')) {
				//	return false;  //stop
				//} else {
					return UE.actionBtn._handle(s.slice(1), this);
				//}
			}
		});
	},
	_handle: function (s, btn) {
		UE.log('action: ' + s);
		var fn = UE.actionBtn.actionList[s];
		if (jQuery.isFunction(fn)) {
			return fn(btn);
		} else {
			return true;  //skip ...uh, seems unnecessary, leaving it undefined seems more proper.
		}
	},
	extend: function (o) {
		if (jQuery.isPlainObject(o)) {
			jQuery.extend(this.actionList, o);
		}
	},
	trigger: function (s) {
		if (s) {
			this._handle(s);
		}
	}
};

//msg
UE.msg = {
	textList: {},
	extend: function (o) {
		if (jQuery.isPlainObject(o)) {
			jQuery.extend(this.textList, o);
		}
	},
	ini: function () {
		this.jMsgWrapper = jQuery('ul.messages');
		this.errorText = '';
		this.successText = '';
		this.codes = [];
		if (this.jMsgWrapper.length) {
			this.jErrorMsg = this.jMsgWrapper.find('.error-msg');
			this.jSuccessMsg = this.jMsgWrapper.find('.success-msg');
			this.errorText = this.jErrorMsg.text();
			this.successText = this.jSuccessMsg.text();
		}
	},
	get: function (s) {
		return this.textList[s] || 'Message: ' + s;
	},
	lookup: function (o, type) {  //o = {errorCode: msgText}
		type = type || 'error';
		var sMsg = (type === 'error') ? this.errorText : this.successText;
		if (jQuery.isPlainObject(o)) {
			jQuery.each(o, function (key, value) {
				if (UE.str.ifHas(sMsg, value)) {
					UE.msg.codes.push(key);
				}
			});
		}
	},
	handle: function (s) {
		if (s) {
			UE.actionBtn.trigger('handle-msg-' + s);
		}
	}
};

//cookie
UE.cookie = UE.cookie || {};
UE.cookie.set = function(sName, sValue, nLiveDays) {
	var sCookieDate = '';
	if (nLiveDays !== undefined) {
		var oDate = new Date();
		oDate.setDate(oDate.getDate() + nLiveDays);
		sCookieDate = ';expires=' + oDate.toGMTString();
	}
	document.cookie = sName + '=' + escape(sValue) + sCookieDate + ';path=/;domain=' + UE.url.rootDomain;
};
UE.cookie.get = function(sName) {
	var sCookie = document.cookie;
	var sValue = '';
	if (sCookie.length > 0) {
		var nStart = sCookie.indexOf(sName + '=');
		var nEnd;
		if (nStart > -1) {
			nStart = nStart + sName.length + 1;
			nEnd = sCookie.indexOf(';', nStart);
			if (nEnd < 0) {
				nEnd = sCookie.length;
			}
			sValue = unescape(sCookie.substring(nStart, nEnd));
		}
	}
	return sValue;
};
UE.cookie.del = function(sName) {
	var sV = UE.cookie.get(sName);
	if (sV) {
		UE.cookie.set(sName, 'null', -1);
	}
};


//tools
UE.tool = UE.tool || {};

(function(){
  var cache = {};
 
  UE.tool.tmpl = function tmpl(str, data){
   // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

//sns
UE.sns = UE.sns || {};
UE.sns.link = {
	weibo: "http://v.t.sina.com.cn/share/share.php?url=[[[url]]]&title=[[[text]]]&appkey=2264487147",
	kaixin: "http://www.kaixin001.com/~repaste/repaste.php?rurl=[[[url]]]&rtitle=[[[text]]]",
	renren: "http://share.renren.com/share/buttonshare.do?link=[[[url]]]&title=[[[text]]]",
	end: null
};
UE.sns.getShareLink = function (site, url, text) {
	var link = '';
	if (site && url && text) {
		var temp = UE.sns.link[site];
		if (temp) {
			link = UE.str.replaceVar(temp, '[[[url]]]', encodeURIComponent(url));
			link = UE.str.replaceVar(link, '[[[text]]]', encodeURIComponent(text));
		}
	}
	return link || false;
};

//dom
UE.dom = UE.dom || {};

//ajax
UE.ajax = UE.ajax || {};
UE.ajax.wait = function (fnCondition, fnCallback) {  //when condition true, trigger fn()
	var bSuccess = false;
	if (jQuery.isFunction(fnCondition) && jQuery.isFunction(fnCallback)) {
		this._waitList.push([fnCondition, fnCallback]);
		if (this._waitList.length === 1) {  //if list is empty (loop is idle) just now, act loop
			UE.ajax._waitLoop();
		}
	}
	return bSuccess;
};
UE.ajax._waitDelay = 1000;  //unit: ms
UE.ajax._waitList = [];
UE.ajax._waitLoop = function () {
	UE.log('ajax wait loop - start');
	UE.log(this._waitList);
	jQuery.each(this._waitList, function (i, n) {
		var fnCondition = n[0];
		var fnCallback = n[1];
		var bSuccess = fnCondition();
		if (bSuccess) {
			fnCallback();
			UE.ajax._waitList[i] = null;
		}
	});
	this._waitList = jQuery.grep(this._waitList, function (n, i) {
		return n;
	});
	if (this._waitList.length) {
		setTimeout(function () {
			UE.ajax._waitLoop();
		}, this._waitDelay);
	}
	UE.log(this._waitList);
	UE.log('ajax wait loop - end');
};
